#include "SerialPortControl.h"

SerialPortControl::SerialPortControl(QObject *parent)
	: QObject(parent)
{
	m_running = false;
	m_serial_worker = NULL;
}

SerialPortControl::~SerialPortControl()
{
	stop();
}

void SerialPortControl::start(const QString& port, DEVICE_CONN_TYPE device_conn_type, int baudRate)
{
	if (m_running)
		return;

	QSharedPointer<SerialInfo> serical_info = QSharedPointer<SerialInfo>::create();
	serical_info->comPort = port;
	serical_info->baudRate = baudRate;
	serical_info->dataBits = 8;
	serical_info->parity = 0;
	serical_info->stopBits = 1;

	m_serial_worker = new ComSerialPport(serical_info, device_conn_type);
	m_serial_worker->moveToThread(&m_workerThread);

	connect(&m_workerThread, &QThread::started, m_serial_worker, &ComSerialPport::slot_started);
	connect(&m_workerThread, &QThread::finished, m_serial_worker, &ComSerialPport::deleteLater);

	connect(m_serial_worker, &ComSerialPport::sig_connection_state, this, &SerialPortControl::sig_connection_state);
	connect(m_serial_worker, &ComSerialPport::sig_receiveDataFromServer, this, &SerialPortControl::sig_receiveDataFromServer);

	connect(this, &SerialPortControl::sig_Reconnect, m_serial_worker, &ComSerialPport::slot_Reconnect);

	if (device_conn_type == DEVICE_CONN_TYPE::ASYNC_AND_TIME_OUT)
	{
		connect(this, &SerialPortControl::sig_AsyncAndWaitSendmessage, m_serial_worker, &ComSerialPport::slot_async_timeout_send_message);
	}
	else if (device_conn_type == DEVICE_CONN_TYPE::ASYNC)
	{
		connect(this, &SerialPortControl::sig_AsyncSendmessage, m_serial_worker, &ComSerialPport::slot_send_message);
	}

	m_workerThread.start();
	m_running = true;
}

void SerialPortControl::reconnect(const QString& com_port, int baudRate)
{
	if (m_serial_worker == NULL)
	{
		return;
	}

	emit sig_Reconnect(com_port, baudRate);
}

void SerialPortControl::stop()
{
	if (m_running == true)
	{
		m_running = false;

		m_workerThread.quit();
		m_workerThread.wait();
		qDebug() << "ֹͣ";
	}
}
